package com.zff.wechat.controller;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.zff.wechat.despatcher.EventDispatcherService;
import com.zff.wechat.despatcher.MsgDispatcherService;
import com.zff.wechat.util.MessageUtil;
import com.zff.wechat.util.SignUtil;

@Controller
@RequestMapping("/wechat")
public class WechatSecurity {

	private static Logger LOG = Logger.getLogger(WechatSecurity.class);
	
	@Autowired
	private MsgDispatcherService msgDispatcherService;
	
	@Autowired
	private EventDispatcherService eventDispatcherService;
	
    @RequestMapping(value = "securit", method = RequestMethod.GET)
    public void doGet(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "signature", required = true) String signature,
            @RequestParam(value = "timestamp", required = true) String timestamp,
            @RequestParam(value = "nonce", required = true) String nonce,
            @RequestParam(value = "echostr", required = true) String echostr) {
        try {
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                PrintWriter out = response.getWriter();
                out.print(echostr);
                out.close();
            } else {
                LOG.info("这里存在非法请求！");
            }
        } catch (Exception e) {
            LOG.error(e, e);
        }
    }

    @RequestMapping(value = "securit", method = RequestMethod.POST)
    public void DoPost(HttpServletRequest request,HttpServletResponse response) {
        try{
            Map<String, String> map=MessageUtil.parseXml(request);
            String msgtype=map.get("MsgType");
            response.setCharacterEncoding("utf-8");

            if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgtype)){
            	String xml = eventDispatcherService.processEvent(map);
            	PrintWriter out = response.getWriter();
                out.print(xml);
                out.flush();
                out.close();
            }else{
                String respXML = msgDispatcherService.processMessage(map);
                PrintWriter out = response.getWriter();
                out.print(respXML);
                out.flush();
                out.close();
            }
        }catch(Exception e){
            LOG.error(e,e);
        }
    }
}